import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';

interface EChartsComponentProps {
    option: echarts.EChartsOption;
    loading?: boolean;
    style?: React.CSSProperties;
}

const EChartsComponent: React.FC<EChartsComponentProps> = ({
    option,
    loading = false,
    style = { width: '100%', height: '400px' },
}) => {
    const chartRef = useRef<HTMLDivElement | null>(null);
    const chartInstanceRef = useRef<echarts.ECharts | null>(null);

    useEffect(() => {
        if (chartRef.current) {
            chartInstanceRef.current = echarts.init(chartRef.current);
            return () => {
                if (chartInstanceRef.current) {
                    chartInstanceRef.current.dispose();
                    chartInstanceRef.current = null;
                }
            };
        }
    }, []);

    useEffect(() => {
        if (chartInstanceRef.current) {
            if (loading) {
                chartInstanceRef.current.showLoading();
            } else {
                chartInstanceRef.current.hideLoading();
                // 增加 option 有效性判断
                if (option && Object.keys(option).length > 0) {
                    chartInstanceRef.current.setOption(option, true);
                }
            }
        }
    }, [option, loading]);

    return <div ref={chartRef} style={style}></div>;
};

export default EChartsComponent;